package com.guzhen.wallpager;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieCompositionFactory;
import com.airbnb.lottie.LottieDrawable;
import com.fun.funlivewallpaper.MainActivity2;
import com.fun.funlivewallpaper.R;

public class ReviewSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
    public static class MyHandlerThread extends HandlerThread implements ValueAnimator.AnimatorUpdateListener {
        private Handler mHandler;
        private Runnable mRunnable;
        private ValueAnimator mValueAnimator;

        public MyHandlerThread(Runnable runnable0) {
            super("SurfaceView2_DrawThread");
            this.mRunnable = runnable0;
        }

        public void cancelAnim() {
            Handler handler0 = this.mHandler;
            if (handler0 != null) {
                handler0.removeCallbacksAndMessages(null);
                this.mHandler = null;
            }

            ValueAnimator valueAnimator0 = this.mValueAnimator;
            if (valueAnimator0 != null) {
                valueAnimator0.removeAllUpdateListeners();
                this.mValueAnimator.cancel();
                this.mValueAnimator = null;
            }
        }

        public void postRunnable(Runnable runnable0) {
            if (this.mHandler == null) {
                this.mHandler = new Handler(this.getLooper());
            }

            this.mHandler.removeCallbacksAndMessages(null);
            this.mHandler.post(() -> this.startRunnableAndAnim(runnable0));
        }

        private void startAnim() {
            if (this.mRunnable != null && this.mValueAnimator == null) {
                ValueAnimator valueAnimator0 = ValueAnimator.ofInt(new int[]{0, 1});
                this.mValueAnimator = valueAnimator0;
                valueAnimator0.setRepeatCount(-1);
                this.mValueAnimator.addUpdateListener(this);
                this.mValueAnimator.start();
            }
        }

        private void startRunnableAndAnim(Runnable runnable0) {
            runnable0.run();
            this.startAnim();
        }

        @Override  // android.animation.ValueAnimator$AnimatorUpdateListener
        public void onAnimationUpdate(ValueAnimator valueAnimator0) {
            this.postRunnable(this.mRunnable);
        }

        @Override
        public void start() {
            synchronized (this) {
                super.start();
            }
        }
    }

    private GestureDetector tapGesturetagDetector;
    private SurfaceHolder mSurfaceHolder;
    private static int dp10;
    private LottieDrawable mLottieDrawable;
    private static int dp180;
    private int halfScreenWidth;
    private MyHandlerThread myHandlerThread;
    private boolean LilIilii;
    private TodayStepHandle todayStep;
    private int screenHeight;
    private boolean isVisible;
    private int screenWidth;
    private Bitmap reviewBgBitmap;
    private Bitmap userDefaultWallpaperBitmap;

    boolean showDefaultUserBg;
    long lastChangeBgTimes = 0L;

    float lottiePlaceX;
    float lottiePlaceY;

    float onDragDistanceX = 0f;
    float onDragDistanceY = 0f;

    static {
        ReviewSurfaceView.dp10 = ScreenHelper.getDimensionPixelSize(R.dimen.gz_dp_10);
        ReviewSurfaceView.dp180 = ScreenHelper.getDimensionPixelSize(R.dimen.gz_dp_180);
    }

    public ReviewSurfaceView(Context context0) {
        this(context0, null);
    }

    public ReviewSurfaceView(Context context0, AttributeSet attributeSet0) {
        this(context0, attributeSet0, -1);
    }

    public ReviewSurfaceView(Context context0, AttributeSet attributeSet0, int v) {
        this(context0, attributeSet0, v, -1);
    }

    public ReviewSurfaceView(Context context0, AttributeSet attributeSet0, int v, int v1) {
        super(context0, attributeSet0, v, v1);
        tapGesturetagDetector = new GestureDetector(context0, new GestureDetector.SimpleOnGestureListener() {
            // 在这里重写你感兴趣的手势方法


            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                try {
                    float x = e1.getX();
                    float y = e1.getY();
                    Rect bounds = mLottieDrawable.getBounds();
                    float lottieRight = bounds.right + lottiePlaceX;
                    float lottieBottom = bounds.bottom + lottiePlaceY;
                    if (x > lottiePlaceX - onDragDistanceX && y > lottiePlaceY - onDragDistanceY && x < lottieRight && y < lottieBottom) {
                        float nextX = lottiePlaceX - (onDragDistanceX + distanceX);
                        float nextY = lottiePlaceY - (onDragDistanceY + distanceY);
                        if (nextX < screenWidth - dp10 && nextX > -bounds.right + dp10 && nextY > dp10 && nextY < screenHeight - dp10) {
                            onDragDistanceX += distanceX;
                            onDragDistanceY += distanceY;
                        }else {
                            onDragDistanceX -= distanceX;
                            onDragDistanceY -= distanceY;
                        }
                        log("onScroll: " + distanceX + " " + distanceY);
                    }
                } catch (Exception ex) {

                }
                return super.onScroll(e1, e2, distanceX, distanceY);
            }

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                try {
                    float x = e.getX();
                    float y = e.getY();
                    log("手指点击: " + x + "," + y);
                    Rect bounds = mLottieDrawable.getBounds();
                    float lottieRight = bounds.right + lottiePlaceX;
                    float lottieBottom = bounds.bottom + lottiePlaceY;
                    log("动画位置:" + lottiePlaceX + "," + lottiePlaceY + " | " + lottieRight + "," + lottieBottom);
                    if (x > lottiePlaceX && y > lottiePlaceY && x < lottieRight && y < lottieBottom) {
                        try {
                            Intent intent = new Intent(context0, MainActivity2.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            context0.startActivity(intent);
                        } catch (Exception eee) {
                            Toast.makeText(context0, "not support", Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (Exception ex) {

                }

                return super.onSingleTapConfirmed(e);
            }
        });
        this.reviewBgBitmap = WallpaperBitmapHelper.getInstance().getreveiew_bg_bitmap();
        int v2 = ScreenUtils.getScreenWidth();
        this.screenWidth = v2;
        this.halfScreenWidth = v2 / 2;
        this.screenHeight = ScreenUtils.getScreenHeight();
//        SurfaceHolder surfaceHolder0 = super.getHolder();
//        this.mSurfaceHolder = surfaceHolder0;
//        surfaceHolder0.addCallback(this);
    }

    private void drawLottie(Canvas canvas0) {
        if (this.mLottieDrawable != null) {
            canvas0.save();
            int v = this.mLottieDrawable.getBounds().width() / 2;
            int v1 = this.mLottieDrawable.getBounds().height();
            lottiePlaceX = (this.halfScreenWidth - v + ReviewSurfaceView.dp10);
            lottiePlaceY = (this.screenHeight - (v1 + ReviewSurfaceView.dp180));
            canvas0.translate(lottiePlaceX - onDragDistanceX, lottiePlaceY - onDragDistanceY);
//            float scale = 1f * canvas0.getWidth() / mLottieDrawable.getComposition().getBounds().width();
//            canvas0.scale(scale, scale);
            this.mLottieDrawable.draw(canvas0);
            canvas0.restore();
        }
    }

    private void drawCanvas(ValueAnimator valueAnimator0) {
        if (myHandlerThread != null) {
            this.myHandlerThread.postRunnable(() -> {
                if (this.isVisible) {
                    Canvas canvas0 = null;
                    SurfaceHolder surfaceHolder0 = this.mSurfaceHolder;
                    try {
                        canvas0 = surfaceHolder0.lockCanvas();
                        try {
                            if (canvas0 != null) {
                                this.drawBackground(canvas0);
                                this.drawLottie(canvas0);
                                this.drawTodayStep(canvas0);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        surfaceHolder0.unlockCanvasAndPost(canvas0);
                    } catch (Throwable unused_ex) {
                        unused_ex.printStackTrace();
                    }

                }
            });
        }
    }

    // Detected as a lambda impl.
    private void drawCanvas() {
        if (this.isVisible) {
            Canvas canvas0 = null;
            SurfaceHolder surfaceHolder0 = this.mSurfaceHolder;
            try {
                canvas0 = surfaceHolder0.lockCanvas();
                try {
                    if (canvas0 != null) {
                        this.drawBackground(canvas0);
                        this.drawLottie(canvas0);
                        this.drawTodayStep(canvas0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                surfaceHolder0.unlockCanvasAndPost(canvas0);
            } catch (Exception unused_ex) {

            }
        }


    }

    private void drawTodayStep(Canvas canvas0) {
        if (this.todayStep == null) {
            this.todayStep = new TodayStepHandle(this.getContext());
        }

        this.todayStep.drawTextKianKa(canvas0);
    }

    @Override  // android.view.SurfaceView
    public SurfaceHolder getHolder() {
        SurfaceHolder surfaceHolder0 = this.mSurfaceHolder;
        return surfaceHolder0 == null ? super.getHolder() : surfaceHolder0;
    }

    public void setHolder(SurfaceHolder surfaceHolder0) {
        this.mSurfaceHolder = surfaceHolder0;
        surfaceHolder0.addCallback(this);
    }

    public void onVisChanged(boolean z) {
        this.isVisible = z;
    }

    private void drawBackground(Canvas canvas0) {
        if (System.currentTimeMillis() - lastChangeBgTimes > 5_000) {
            if (lastChangeBgTimes != 0) {
                showDefaultUserBg = !showDefaultUserBg;
            }
            lastChangeBgTimes = System.currentTimeMillis();
        }
        if (showDefaultUserBg) {
            drawUserOrgDefaultWallpaper(canvas0);
        } else {
            Bitmap bitmap0 = WallpaperBitmapHelper.getInstance().getreveiew_bg_bitmap();
            this.reviewBgBitmap = bitmap0;
            canvas0.drawBitmap(bitmap0, 0.0f, 0.0f, null);
        }
    }

    @SuppressLint("MissingPermission")
    private void drawUserOrgDefaultWallpaper(Canvas canvas0) {
        Bitmap bitmap0 = WallpaperBitmapHelper.getInstance().getUserDefautWallpaper();
        this.userDefaultWallpaperBitmap = bitmap0;
        if (bitmap0 == null) {
            WallpaperManager wallpaperManager0 = WallpaperManager.getInstance(this.getContext());
            try {
                this.userDefaultWallpaperBitmap = ((BitmapDrawable) wallpaperManager0.getDrawable()).getBitmap();
                RectF rectF0 = new RectF(0.0f, 0.0f, ((float) this.screenWidth), ((float) this.screenHeight));
                canvas0.drawBitmap(this.userDefaultWallpaperBitmap, null, rectF0, null);
            } catch (Exception exception0) {
                exception0.printStackTrace();
            }

            return;
        }

        RectF rectF1 = new RectF(0.0f, 0.0f, ((float) this.screenWidth), ((float) this.screenHeight));
        canvas0.drawBitmap(this.userDefaultWallpaperBitmap, null, rectF1, null);
    }


    private void ilIIL1IiL() {
        this.drawCanvas();
        this.setAndStatLottie();
    }

    private void setAndStatLottie() {
        LottieDrawable lottieDrawable0 = new LottieDrawable();
        this.mLottieDrawable = lottieDrawable0;
        lottieDrawable0.enableMergePathsForKitKatAndAbove(true);
//        lottieDrawable0.setMinAndMaxFrame(0, 40);
        LottieComposition l1LIl0 = (LottieComposition) LottieCompositionFactory.fromRawResSync(this.getContext(), R.raw.live2_boy).getValue();
//        LottieComposition l1LIl0 = (LottieComposition) LottieCompositionFactory.fromRawResSync(this.getContext(), R.raw.live1_finger).getValue();
        this.mLottieDrawable.setComposition(l1LIl0);
        this.mLottieDrawable.setRepeatCount(-1);
        this.mLottieDrawable.setBounds(0, 0, ScreenHelper.getDimensionPixelSize(R.dimen.gz_dp_192), ScreenHelper.getDimensionPixelSize(R.dimen.gz_dp_284));
        this.mLottieDrawable.addAnimatorUpdateListener(this::drawCanvas);
//        this.mLottieDrawable.start();
        this.mLottieDrawable.playAnimation();

    }

    @Override  // android.view.View
    public boolean onTouchEvent(MotionEvent motionEvent0) {
//        return super.onTouchEvent(motionEvent0);
        tapGesturetagDetector.onTouchEvent(motionEvent0);

        return true;
    }

    @Override  // android.view.SurfaceHolder$Callback
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
    }

    @Override  // android.view.SurfaceHolder$Callback
    public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder0) {
        MyHandlerThread reviewSurfaceView$lIlI1liIIL0 = this.myHandlerThread;
        if (reviewSurfaceView$lIlI1liIIL0 != null) {
            reviewSurfaceView$lIlI1liIIL0.cancelAnim();
            this.myHandlerThread.quitSafely();
            this.myHandlerThread = null;
        }

        MyHandlerThread reviewSurfaceView$lIlI1liIIL1 = new MyHandlerThread(null);
        this.myHandlerThread = reviewSurfaceView$lIlI1liIIL1;
        reviewSurfaceView$lIlI1liIIL1.start();
        this.myHandlerThread.postRunnable(() -> this.ilIIL1IiL());


    }

    public static void log(String msg) {
        Log.i("suuuuuuu", msg);

    }

    @Override  // android.view.SurfaceHolder$Callback
    public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder0) {
        synchronized (this) {
            MyHandlerThread mm = this.myHandlerThread;
            if (mm != null) {
                mm.quitSafely();
                this.myHandlerThread = null;
            }

            LottieDrawable lottieDrawable0 = this.mLottieDrawable;
            if (lottieDrawable0 != null) {
                lottieDrawable0.removeAllAnimatorListeners();
                this.mLottieDrawable.cancelAnimation();
                this.mLottieDrawable = null;
            }

            return;
        }
    }
}

